package com.miya.demo.service.impl;

import cn.hutool.json.JSONUtil;
import com.miya.demo.common.exception.BusinessException;
import com.miya.demo.service.PushMsgService;
import com.miya.demo.support.netty.bean.ChatMsg;
import com.miya.demo.support.netty.bean.DataContent;
import com.miya.demo.support.netty.config.UserConnectPool;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 消息推送imp
 *
 * @author CaiXiaowei
 * @date 2023/5/9
 */
@Service
public class PushMsgServiceImpl implements PushMsgService {

    @Override
    public void pushMsgToOne(DataContent dataContent) {
        ChatMsg chatMsg = dataContent.getChatMsg();
        Channel channel = UserConnectPool.getChannel(chatMsg.getReceiverId());
        if (Objects.isNull(channel)) {
            throw new BusinessException("未连接socket服务器");
        }

        channel.writeAndFlush(
                new TextWebSocketFrame(
                        JSONUtil.toJsonStr(chatMsg)
                )
        );
    }

    @Override
    public void pushMsgToAll(DataContent dataContent) {
        ChatMsg chatMsg = dataContent.getChatMsg();
        UserConnectPool.getChannelGroup().writeAndFlush(
                new TextWebSocketFrame(
                        JSONUtil.toJsonStr(chatMsg)
                )
        );
    }

}
